"""
文件系统变化监听器。
"""
import asyncio
from .core import get_event_loop
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class AsyncFileEventListener(FileSystemEventHandler):
    def __aiter__(self):
        return self

    def __anext__(self):
        if not self.observer:
            raise StopAsyncIteration('Observer is destroyed.')
        if self.future.done():
            self.future = self.loop.create_future()
        return self.future

    def __init__(self, path, conditions):
        FileSystemEventHandler.__init__(self)
        self.conditions = conditions
        self.observer = Observer()
        self.observer.schedule(self, path, recursive=True)
        self.loop = get_event_loop()
        self.future = self.loop.create_future()
        self.observer.start()

    def on_any_event(self, event):
        if self.conditions(event):
            self.loop.call_soon_threadsafe(self.future.set_result, event)

    async def destroy(self):
        """
        销毁文件监听。
        """
        if not self.observer:
            return
        self.observer.stop()
        self.observer.join()
        self.observer = None


async def main():
    """
    测试示例。
    """
    listener = AsyncFileEventListener('./', lambda x: True)
    async for event in listener:
        print(event)
    await listener.destroy()


if __name__ == '__main__':
    asyncio.run(main())
